<template>
  <div class="list-content">
    <el-row type="flex" justify="space-between">
      <el-form class="serach-form" :inline="true" :model="formInline" @submit.native.prevent>
        <!-- <el-form-item v-if="isMuilUnitUser">
          <el-select clearable filterable @change="getList(1)" v-model="formInline.orgId" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgOptionsAll"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-select clearable filterable @change="getList(1)" v-model="formInline.label" placeholder="全部标签">
            <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select clearable @change="getList(1)" v-model="formInline.status" placeholder="全部状态">
            <el-option label="在用" value="1"></el-option>
            <el-option label="停用" value="2"></el-option>
            <el-option label="结束" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="formInline.queryContent"
            placeholder="计划名称"
            @keyup.enter.native="getList(1)"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getList(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="more-btns" v-if="showEdit">
        <!-- <el-button type="text" @click="handleOpenDialog('PlanHelper')" style="text-decoration:underline;">如何创建计划？</el-button> -->
        <el-button type="primary" @click="addPlan()">新增</el-button>
      </div>
    </el-row>
    <el-row class="overclick-wrap" :gutter="40" type="flex" justify="space-between">
      <el-col :span="8">
        <div class="item-wrap" style="cursor:default;">
          <div class="item-content">
            <p class="item-value color-1">{{ orgOptions.length }}</p>
            <p class="item-title">单位数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap" style="cursor:default;">
          <div class="item-content">
            <p class="item-value color-2">{{ total }}</p>
            <p class="item-title">计划总数</p>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="item-wrap" style="cursor:default;">
          <div class="item-content">
            <p class="item-value color-4">{{ Math.round(Number(total/(orgOptions.length||1))) }}</p>
            <p class="item-title">单位平均计划数</p>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-table v-show="total>0" v-loading="loading" :data="tableData" ref="mainTable" style="width: 100%">
      <el-table-column label="序号" type="index" width="60"></el-table-column>
      <el-table-column prop="name" label="计划名称"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="util.transInspectPlanStatusTag(scope.row.status)"
            disable-transitions
          >{{util.transInspectPlanStatus(scope.row.status)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="labelName" label="标签"></el-table-column>
      <el-table-column label="责任人">
        <template v-slot="sc">{{sc.row.lliableName}}</template>
      </el-table-column>
      <el-table-column prop="planPointsId" label="含点位数">
        <template v-slot="sc">{{sc.row.planPointsId?sc.row.planPointsId.split(',').length:''}}</template>
      </el-table-column>
      <el-table-column label="开始日期" width="160">
        <template slot-scope="sc">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ util.ilinkTimeformat.format(new Date(sc.row.startTime),'yyyy-MM-dd') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" width="160">
        <template slot-scope="sc" v-if="sc.row.endTime">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ util.ilinkTimeformat.format(new Date(sc.row.endTime),'yyyy-MM-dd') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="handleOpenDialog('PlanDetail',scope.row)" type="text" size="small">详情</el-button>
          <template v-if="showEdit">
            <span v-if="scope.row.status==1||scope.row.status==2" class="dividing-line">|</span>
            <el-button
              v-if="scope.row.status==1||scope.row.status==2"
              @click="handleOpenDialog('PlanEdit',scope.row)"
              type="text"
              size="small"
            >修改</el-button>
            <span class="dividing-line">|</span>
            <el-button
              @click="addPlan(scope.row)"
              type="text"
              size="small"
            >复制</el-button>
            <span v-if="scope.row.status!=3" class="dividing-line">|</span>
            <el-button
              v-if="scope.row.status!=3"
              @click="stopPlan(scope.$index, scope.row)"
              type="text"
              size="small"
            >{{scope.row.status==1?'停用':'启用'}}</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="delPlan(scope.$index, scope.row)" type="text" size="small">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="total>0"
      background
      @size-change="sizeChange"
      @current-change="pageChange"
      :current-page="formInline.currentPageIndex"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <div v-show="showEmpty&&total==0" class="text-center">
      <img
        src="../../../assets/images/inspect/no-plan.png"
        style="margin-top:calc(50vh - 418px);width:600px;height:427px;"
      />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="新增巡检计划"
      width="800px"
      top="10vh"
      v-if="dialogFalg"
      :visible.sync="dialogFalg"
      @close="closeDialog"
      v-dialogDrag
    >
      <edit-form
        :organizationId="formInline.orgId"
        :label-list="labelList"
        :editInfo="editInfo"
        :closeDialog="closeDialog"
      ></edit-form>
    </el-dialog>
    <plan-helper ref="PlanHelper" v-if="dialogVisible.PlanHelper"></plan-helper>
    <plan-edit ref="PlanEdit" v-if="dialogVisible.PlanEdit" @refreshDataList="getList(1)"></plan-edit>
    <plan-detail ref="PlanDetail" v-if="dialogVisible.PlanDetail"></plan-detail>
  </div>
</template>

<script>
import {
  getInspectPlanList,
  delInspectPlan,
  isEnable,
  getPointLabelList,
} from '@/api/inspectx'
import util from '@/utils/util'
import EditForm from '../Dialog/InspectPlanForm'
import PlanDetail from '../Dialog/PlanDetail'
import PlanEdit from '../Dialog/PlanEdit'
import PlanHelper from '../Dialog/PlanHelper'
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'InspectPlanList',
  props: {
    organizationId: {
      required: false,
    },
    organizationName: {
      default() {
        return ''
      },
    },
    hasFather: {
      type: Boolean,
      default() {
        return false
      },
    },
    returnFun: {
      type: Function,
      default() {
        return () => {}
      },
    },
  },
  components: {
    EditForm,
    PlanHelper,
    PlanEdit,
    PlanDetail,
  },
  data() {
    return {
      showEmpty: false,
      freashFlag: 0,
      dayBox: {
        1: '周一到周五开始时间是',
        6: '每周六开始时间是',
        7: '每周日开始时间是',
      },
      formInline: {
        orgId: '',
        queryContent: '',
        currentPageSize: 10,
        currentPageIndex: 1,
        label: '',
        status: '',
      },
      total: 0,
      util: util,
      accountName: this.$store.state.userinfo.accountName,
      defaultImg: this.GLOBAL.defaultImg,
      tableData: [], //表格数据
      detailObj: {}, //展开详情
      loading: false,
      dialogFalg: false,
      editInfo: {}, // 编辑对应的表单信息
      dialogVisible: {
        PlanHelper: false,
        PlanEdit: false,
        PlanDetail: false,
      },
      labelList: [],
    }
  },
  computed: {
    ...mapState([
      'orgOptions',
      'buttonPermission',
      'currentTabName',
      'userinfo',
    ]),
    ...mapGetters([
      'isMuilUnitUser',
      'userOrgId',
      'userOrgIds',
      'orgOptionsAll',
      'userFullOrgIds',
    ]),
    showEdit() {
      return (
        this.buttonPermission[this.currentTabName].indexOf(
          'inspectionManager'
        ) > -1
      )
    },
  },
  created: function () {
    this.formInline.orgId = this.userFullOrgIds
    this.getPointLabelList()
    this.getList(1)
  },
  methods: {
    getPointLabelList() {
      getPointLabelList({ type: 1 }).then((res) => {
        this.labelList = res.data || []
      })
    },
    handleOpenDialog(key, data) {
      this.dialogVisible[key] = true
      this.$nextTick(() => {
        this.$refs[key].init(data)
      })
    },
    sizeChange(_pageSize) {
      //页码切换
      this.getList(1, _pageSize)
    },
    pageChange(_pageIndex) {
      //翻页
      this.getList(_pageIndex)
    },
    getList(_pageIndex, _pageSize) {
      //获取列表
      if (_pageIndex) {
        this.formInline.currentPageIndex = _pageIndex
      }
      if (_pageSize) {
        this.formInline.currentPageSize = _pageSize
      }
      this.loading = true
      getInspectPlanList({
        queryType: 1,
        orgIds: this.formInline.orgId,
        queryContent: this.formInline.queryContent,
        pageIndex: this.formInline.currentPageIndex - 1,
        pageSize: this.formInline.currentPageSize,
        status: this.formInline.status,
        label: this.formInline.label,
      }).then((result) => {
        this.total = result.total
        this.tableData = result.data
        this.loading = false
        this.showEmpty = true
      })
    },
    addPlan(row) {
      this.dialogFalg = true
      this.editInfo = Object.assign({},row || {})
    },
    stopPlan(index, row) {
      let that = this
      this.$confirm(row.status == 1 ? '停用当前计划' : '启用当前计划', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        roundButton: true,
      })
        .then(() => {
          isEnable({
            id: row.id,
            status: row.status == 1 ? 2 : 1,
            account: this.userinfo.accountName,
          }).then((res) => {
            if (res.status === 200) {
              that.$message({
                type: 'success',
                message: '操作成功!',
              })
              if (this.formInline.status == 1 || this.formInline.status == 2) {
                if (this.tableData.length == 1) {
                  if (this.formInline.currentPageIndex > 1)
                    this.formInline.currentPageIndex--
                }
              }
              that.getList()
            } else {
              that.$message.error(res.info)
            }
          })
        })
        .catch(() => {})
    },
    delPlan(index, row) {
      let that = this
      this.$confirm('删除后，已生成的巡检任务仍然存在。建议停用。', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        roundButton: true,
      })
        .then(() => {
          delInspectPlan({
            id: row.id,
            account: this.userinfo.accountName,
          }).then((res) => {
            if (res.status === 200) {
              if (res.data === 200011) {
                this.$message({
                  message: '该巡检计划已启动，不能删除！',
                  type: 'warning',
                })
              } else {
                that.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                if (this.tableData.length == 1) {
                  if (this.formInline.currentPageIndex > 1)
                    this.formInline.currentPageIndex--
                }
                that.getList()
              }
            } else {
              that.$message.error(res.info)
            }
          })
        })
        .catch(() => {})
    },
    closeDialog(refresh) {
      this.dialogFalg = false
      if (refresh) {
        this.getList(this.editInfo.id ? '' : 1)
      }
    },
  },
}
</script>